package com.puppet.building182.aspects;

import com.alibaba.fastjson2.JSON;
import com.puppet.building182.pojo.Log;
import com.puppet.building182.service.LogService;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.logging.log4j.LogBuilder;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Arrays;

@Component
@Aspect
public class LogAspect {
    @Autowired
    private LogService logService;

    //    定义切入点
    @Pointcut("execution (public * com.puppet.building182.controller.*.*(..))")
    public void pointcut() {

    }

    @Around("pointcut()")
    public Object addLog(ProceedingJoinPoint pjp) throws Throwable {
        System.out.println("开始记录日志===================");
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String reType = request.getMethod();
        String url = request.getRequestURI();
        if(url.startsWith("/log")){
            return pjp.proceed();
        }
        String fullClass = pjp.getTarget().getClass().getName();
        String methodName = pjp.getSignature().getName();
        String reqParams = Arrays.toString(pjp.getArgs());
        Object proceed = pjp.proceed();
        String respData = JSON.toJSONString(proceed);
        Log log = Log.builder().reqType(reType).fullClass(fullClass).method(methodName).reqParams(reqParams).
                respData(respData).reqUrl(url).build();
        System.out.println(log);
        logService.addLog(log);
        return proceed;
    }


}
